package com.biwin.module.security.starter.handler;

import cn.hutool.json.JSONUtil;
import com.biwin.common.app.enums.BwSecurityExceptionEnum;
import com.biwin.common.app.vo.BwResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Authentication Entry point
 *
 * @author biwin
 * @since 0.0.1
 */
@Component
public class BwAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {

//        BwResponse bwResponse = null;
//        if (e instanceof AuthorizationServiceException) {
//            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
//            bwResponse = BwResponse.response(BwSecurityExceptionEnum.USER_NOT_LOGIN);
//        } else if (e instanceof AccessDeniedException) {
//            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
//            bwResponse =
        //            BwResponse.response(BwSecurityExceptionEnum.NO_PERMISSIONS);
//        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        BwResponse bwResponse = BwResponse.response(BwSecurityExceptionEnum.USER_NOT_LOGIN);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSONUtil.toJsonStr(bwResponse));
    }
}
